package com.imooc.course.server.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.Resource;
import java.io.IOException;

@SpringBootConfiguration
public class SqlSessionFactoryConfig {

    @Resource(name = "data_Source")
    private ComboPooledDataSource dataSource;
    @Value("${mybatis.mapper_locations}")
    private String mapper_locations;
    @Value("${mybatis.base_package}")
    private String base_package;
    @Value("${mybatis.config_location}")
    private String config_location;
    @Value("${mybatis.logDisplaySQL}")
    private String logDisplaySQL;

    private PathMatchingResourcePatternResolver PMRPR;

    private PathMatchingResourcePatternResolver getPMRPR() {
        if (PMRPR == null) {
            PMRPR = new PathMatchingResourcePatternResolver();
        }
        return PMRPR;
    }

    private String getMapperLocations() {
        return ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapper_locations;
    }

    @Bean
    public SqlSessionFactoryBean getSqlSessionFactory() throws IOException {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setConfigLocation(new ClassPathResource(config_location));
        sessionFactory.setMapperLocations(getPMRPR().getResources(this.getMapperLocations()));
        //在日志中显示SQL语句
        if ("true".equalsIgnoreCase(logDisplaySQL)) {
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setLogImpl(StdOutImpl.class);
        }
        return sessionFactory;
    }
}
